<?php
namespace app\erp\model;

use think\Model;
use traits\model\SoftDelete;
use app\erp\validate\Siterule;
use think\Cache;

class Sitedb extends Model
{
    use SoftDelete;

    protected $deleteTime = 'delete_time';

    protected $pk = 'site_id';

    protected $name = 'site';

    protected $type = [
        'create_time' => 'timestamp:Y-m-d',
        'delete_time' => 'timestamp:Y-m-d'
    ];

    protected $autoWriteTimestamp = true;

    protected $insert = [
        'partner_id' => PARTNER_ID
    ];

    public $param = array();

    protected function cache_name($name)
    {
        $new_arr = $this->param;
        $new_arr['partner_id'] = PARTNER_ID;
        if (! isset($new_arr['site_id'])) {
            $new_arr['site_id'] = SITE_ID;
        }
        ksort($new_arr);
        $param_str = http_build_query($new_arr);
        return md5($name . $param_str);
    }

    public function scopeSiteId($query, $site_id)
    {
        $query->where('site_id', $site_id);
    }
    public function scopeGoodsAudit($query,$goods_audit){
        $query->where('goods_audit',$goods_audit);
    }
    // 基础查询
    public function base($query)
    {
        $field = $this->getDeleteTimeField(true);
        if ($field) {
            if (isset($this->param['delete']) && $this->param['delete'] == 'yes') {
                $this->onlyTrashed();
            } else {
                $query->useSoftDelete($field);
            }
        }
        $query->where('partner_id', PARTNER_ID);
        if (isset($this->param['site_id']) && $this->param['site_id']) {
            $query->where('site_id', $this->param['site_id']);
        }
        if(isset($this->param['site_name']) && $this->param['site_name']){
            $query->siteName($this->param['site_name']);
        }
        if(isset($this->param['site_http']) && $this->param['site_http']){
            $query->siteHttp($this->param['site_http']);
        }
        if(isset($this->param['goods_audit']) && $this->param['goods_audit']){
            $query->goodsAudit($this->param['goods_audit']);
        }
    }
    // 查询分站名称
    public function scopeSiteName($query, $siteName)
    {
        $query->where('site_name', 'like', '%' . $siteName . '%');
    }
    // 查询分站域名
    public function scopeSiteHttp($query, $siteHttp)
    {
        $query->where('site_http', 'like', '%' . $siteHttp . '%');
    }
    // 查询列表
    public function ajaxSelect()
    {
        if (isset($this->param['site_name']) && ! empty($this->param['site_name'])) {
            $this->siteName($this->param['site_name']);
        }
        if (isset($this->param['site_http']) && ! empty($this->param['site_http'])) {
            $this->siteHttp($this->param['site_http']);
        }
        $data = $this->order($this->param['_o'], $this->param['_b'])
            ->cache($this->cache_name('site_select'), 86400, 'site')
            ->page($this->param['page'], $this->param['limit'])
            ->select();
        $count = $this->count();
        if (! $data->isEmpty()) {
            $data = $data->toArray();
            foreach ($data as $key => $val) {
                $data[$key] = $this->handleData($val);
            }
        }
        $return['data'] = $data;
        $return['count'] = $count;
        return $return;
    }

    /**
     *
     * @todo 获取详情
     */
    public function ajaxFind($site_id)
    {
        if (empty($site_id) || $site_id == 0) {
            $data['site_name'] = '主站';
            return $data;
        }
        $data = $this->where('site_id', $site_id)->find();
        if ($data) {
            $data = $data->toArray();
            $time = strtotime($data['create_time']) + $data['site_update']*86400*365;
            chk_date_password($time);
            $data = $this->handleData($data);
            return $data;
        } else {
            $data['delete_flag'] = true;
            return $data;
        }
    }
    // 保存分站token
    public function ajaxSaveToken()
    {
        $this->allowField(true)
            ->where('site_id', $this->param['site_id'])
            ->update($this->param);
        return 'success';
    }

    public function ajaxChkToken($token)
    {
        $get_info = $this->master()->find();
        if (! $get_info) {
            return '分站错误';
        }
        if ($get_info['access_token'] != $token) {
            return 'token错误';
        }
        /*
        if (time() > $get_info['expires_stop_time']) {
            return 'token_expired';
        }
        */
        return 'success';
    }

    /**
     *
     * @todo 保存数据
     */
    public function ajaxSave($param)
    {
        $param['master_site_goods'] = isset($param['master_site_goods']) && $param['master_site_goods'] ? 1 : 2;
        $param['goods_alone'] = isset($param['goods_alone']) && $param['goods_alone'] ? 1 : 2;
        $param['goods_audit'] = isset($param['goods_audit']) && $param['goods_audit'] ? 1 : 2;
        if ($param['goods_alone'] == 1) {
            $param['goods_audit'] = 2;
        }
        $rule = new Siterule();
        $param['partner_id'] = PARTNER_ID;
        if (! $rule->check($param)) {
            return $rule->getError();
        }
        unset($param['partner_id']);
        if (isset($param['site_id']) && $param['site_id'] != '') {
            $site_id = $param['site_id'];
            unset($param['site_id']);
            $this->save($param, [
                'site_id' => $site_id
            ]);
        } else {
            $this->allowField(true)->save($param);
        }
        Cache::clear('site');
        return 'success';
    }
    // 软删除
    public function ajaxDelete()
    {
        if (isset($this->param['site_id'])) {
            if (isset($this->param['delete']) && $this->param['delete'] == 'yes') {
                $this->destroy(function ($query) {
                    $query->where('site_id', 'IN', $this->param['site_id']);
                }, true);
            } else {
                $this->destroy(function ($query) {
                    $query->where('site_id', 'IN', $this->param['site_id']);
                });
            }
            Cache::clear('site');
        }
    }
    // 恢复数据
    public function ajaxRestore()
    {
        if (isset($this->param['site_id'])) {
            $map[$this->pk] = array(
                'IN',
                $this->param['site_id']
            );
            $this->restore($map);
            Cache::clear('site');
        }
    }
    // 数据处理
    protected function handleData($val)
    {
        foreach ($val as $k => $v) {
            $val[$k] = $v;
            switch ($k) {
                case 'master_site_goods':
                    $val['master_site_goods_text'] = $v == 1 ? '可获取' : '不可获取';
                    break;
                case 'goods_alone':
                    $val['goods_alone_text'] = $v == 1 ? '独立' : '关联';
                    break;
                case 'goods_audit':
                    $val['goods_audit_text'] = $v == 1 ? '需要' : '不需要';
                    break;
                default:
                    break;
            }
        }
        return $val;
    }
}